<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>用数据渲染tab页</title>
    <style>
        body {
            margin: 0;
        }
        .tab-head {
            width: 100vw;
            height: 50px;
            display: grid;
            /* 这句话等会用js加上 */
            grid-template-columns: repeat(3, 1fr);
        }
        .tab-head .item {
            background: #e8e8e8;
            text-align: center;
            line-height: 50px;
            font-weight: 900;
        }
        .tab-head .item.active {
            background: #e8aaaa;
        }
        .tab-body {
            width: 100vw;
            height: 100px;
            background: #f5f5f5;
        }
        .tab-body .item {
            display: none;
        }
        .tab-body .item.active {
            display: block;
        }
    </style>
</head>
<body>
    <div class="tab-head"></div>
    <div class="tab-body"></div>

    <script>
        const data = [
            {
                tabName: 'aa',
                content: 'content a<br>content a<br>content a<br>content a<br>',
            },
            {
                tabName: 'bb',
                content: 'content b<br>content b<br>content b<br>content b<br>',
            },
            {
                tabName: 'cc',
                content: 'content c<br>content c<br>content c<br>content c<br>',
            },
        ];
        const head = document.querySelector('.tab-head');
        const body = document.querySelector('.tab-body');

        for (let i = 0; i < data.length; i++) {
            const item = data[i];
            //// 添加head项
            // 创建一个class为item的div
            const headItem = document.createElement('div');
            headItem.setAttribute('class', 'item' + (i === 0 ? ' active' : ''));
            headItem.innerText = item.tabName;
            // 把制作好的div追加至head
            head.appendChild(headItem);
            //// 添加body项
            const bodyItem = document.createElement('div');
            bodyItem.setAttribute('class', 'item' + (i === 0 ? ' active' : ''));
            bodyItem.innerHTML = item.content;
            body.appendChild(bodyItem);

            // 绑定事件
            headItem.addEventListener('click', function () {
                // 处理head
                const headItems = document.querySelectorAll('.tab-head .item');
                // 处理body
                const bodyItems = document.querySelectorAll('.tab-body .item');
                for (let i = 0; i < headItems.length; i++) {
                    headItems[i].setAttribute('class', 'item');
                    bodyItems[i].setAttribute('class', 'item');
                }
                headItem.setAttribute('class', 'item active');
                bodyItem.setAttribute('class', 'item active');
            });
        }

    </script>

</body>
</html>